package com.itheima.filter;


import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.entity.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "loginFilter" ,urlPatterns = "/*")
@Slf4j
public class loginCheckFilter implements Filter {

    private static final AntPathMatcher anto=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        //1.获取本次请求的URI
        String uri=request.getRequestURI();
        log.info("拦截到了："+request.getRequestURL());

        //2.定义不需要被拦截的路径
        String[] uris=new String[]
                {
                "/employee/login",
                        "/employee/logout",
                        "/backend/**",
                        "/front/**",
                        "/common/**",
                        "/user/sendMsg",
                        "/user/login"
        };

        //3.判断本次请求是不是需要处理
        boolean is=isFilter(uris,uri);
        //直接放行
        if (is){
            filterChain.doFilter(request,response);
            log.info("不需要处理的请求：{}",request.getRequestURI());
            return;
        }


        //session里面有东西     直接放行
        if (request.getSession().getAttribute("Employee")!=null){
            Object obj=request.getSession().getAttribute("Employee");
            Long empid= (Long) obj;
            BaseContext.setThreadLocal(empid);
            filterChain.doFilter(request,response);

            log.info("用户已登录，用户的id是："+request.getSession().getAttribute("Employee"));
            return;
        }

        Object obj1=request.getSession().getAttribute("user");

        //session里面有东西     直接放行
        if (obj1!=null){
            Long userid= (Long) obj1;
            BaseContext.setThreadLocal(userid);
            filterChain.doFilter(request,response);

            log.info("用户已登录，用户的id是："+request.getSession().getAttribute("user"));
            return;
        }

        //如果session里面没有东西 那么就必须拦截并且 跳转页面  写回一个JSON数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        log.info("用户未登录，请求页面是："+request.getRequestURL());
        return;
    }

    //判断是不是需要进行处理
    public boolean isFilter(String[] urls,String url){
        for (String s:
             urls) {
            if (anto.match(s,url)){
                return true;
            }
        }
        return false;
    }
}
